let dateIn = ""
let home = ""
$NG.AllReady(function (page, { useDataIndexChange, useUpdateRow, useValuesChange, useUpdateRows }) {
    const mstform = $NG.getCmpApi("p_form_visit_plan_m")
    const grid = $NG.getCmpApi("p_form_visit_plan_d")
    let cityMap = {}
    let phidPc = null
    let gxrArr = []
    let gxrScArr = []
    getAllGxr()
    getGxrInfo()
    if (page.oType == 'add') {
        $NG.updateState((updater) => {
            updater.data.p_form_visit_plan_m.setProps({
                bill_name: `${mstform.getItem("phid_org").getText()}-${mstform.getItem("bill_dt").getValue()}-现场回访计划`,
                u_act_qty: 0
            })
        })
    }
    $NG.updateUI((updater) => {
        const fields = ["u_jump", "u_dbclick"];
        console.log(updater, "qf");
        fields.forEach((field) => {
            updater.editGrid.p_form_visit_plan_d[field].setProps({
                // hidden: true, //隐藏
                // required: true, //必输
                disabled: false, //只读
            });
        });
    });

    console.log(`获取表体信息`, $NG.getPageState());
    // setInterval(()=>{
    //     const datasss = $NG.getCmpApi("p_form_visit_plan_m");
    //     
    // },2000)

    $NG.updateUI(updater => {
        updater.editGrid.p_form_visit_plan_d.u_dbclick.setProps((p) => {
            return {
                ...p, editor: {
                    ...p.editor,
                    onDoubleClick() {
                        $NG.open("http://nginx.clouddev.hisense.com/react/index.html#/customform/list?busType=EFORM9000000092&issso=1&AppTitle=%E7%8E%B0%E5%9C%BA%E6%8B%9C%E8%AE%BF%E8%AE%B0%E5%BD%95")
                        console.log('双击成功!!!!!', window.location.href);
                    }
                }
            }
        })
    })
    $NG.updateUI(updater => {
        updater.editGrid.p_form_visit_plan_d.u_jump.setProps((p) => {
            return {
                ...p, editor: {
                    ...p.editor,
                    onDoubleClick() {
                        const title = "现场拜访记录-新增"
                        const origin = window.location.href.split("#")[0]
                        const arrD = grid.getRows()
                        let it = null;
                        const _tempArr = []
                        function openWindow(){
                            const bookId = $NG.getPageState().data.p_form_visit_plan_m.phid
                            const bookName = $NG.getPageState().data.p_form_visit_plan_m.bill_name
                            const param = `#/customform/detail?otype=add&busType=EFORM9000000092&isSso=1&AppTitle=${encodeURIComponent(title)}
                        &treeOcode=${$NG.getUser().orgID}&treeOcodeName=${encodeURIComponent($NG.getUser().orgName)}
                                        &treePc=&treePcName=&u_gxr_name=${it.u_plan_visit_ps_EXName}&u_gxr=${it.u_plan_visit_ps}
                                        &phidName=${it.phid_pc_EXName}&phidPc=${it.phid_pc}&sourceId=${$NG.getCmpApi("p_form_visit_plan_d").getSelectedRow().phid}
                                        &bookId=${$NG.getCmpApi("p_form_visit_plan_d").getSelectedRow().phid}&bookName=${bookName}&inType=click`
                            $NG.open(origin + param)
                        }
                        arrD.forEach((item, index) => {
                            if (item.checked) {
                                _tempArr.push(index + 1)
                                it = item
                            }
                        })
                        if (it) {
                            if (_tempArr.length > 1) {
                                $NG.alert('查看详细请勿选择多行！')
                            } else if (_tempArr.length == 1 && currentStatus()) {
                                console.log(`测试表体`, $NG.getCmpApi("p_form_visit_plan_d").getSelectedRow());
                                $NG.execServer("getGzzcbdt",{phid:mstform.getItem("phid_cycle").getValue()},(resq)=>{
                                    console.log(`刹时间`,resq);
                                    const dt = JSON.parse(resq.data)[0].extendObjects.bdt.substring(0,7).trim()
                                    $NG.execServer("getXcInfo", { id: $NG.getCmpApi("p_form_visit_plan_d").getSelectedRow().phid,date:'2025-03' }, function (res) {
                                    console.log(`截取的时间`,dt,$NG.getCmpApi("p_form_visit_plan_d").getSelectedRow().phid);
                                    console.log(`新增情况`,res);
                                        if (res.count == 0) {
                                            console.log(`获取表体信息`, $NG.getPageState(), it)
                                            openWindow()
                                        } else {
                                            const _data= JSON.parse(res.data)
                                            let lock = false
                                            _data.forEach((item)=>{
                                                if(item.extendObjects.u_visot_time.substring(0,7) == dt){
                                                    lock = true
                                                }
                                            })
                                            if (!lock) {
												openWindow();
											} else {
												// 确认提示框
												$NG.confirm(
													"本月已包含拜访计划，是否继续新增？"
												).then(function (result) {
													if (result) {
												        openWindow();
													}
												});
											}
                                            
    
                                            //     const _data = JSON.parse(res.data)[0].extendObjects
                                            //     if (_data.app_status == 1) {
                                            //         console.log(`查看`);
                                            //         const datas = JSON.parse(res.data)[0].extendObjects
                                            //         const param = `#/customform/detail?id=${datas.phid}&otype=view&busType=EFORM9000000092&isSso=1&AppTitle=${encodeURIComponent("现场拜访记录-查看")}
                                            // &sourceId=${$NG.getCmpApi("p_form_visit_plan_d").getSelectedRow().phid}&inType=click`
                                            //         $NG.open(origin + param)
    
                                            //     } else {
                                            //         console.log(`修改`);
                                            //         const datas = JSON.parse(res.data)[0].extendObjects
                                            //         const param = `#/customform/detail?id=${datas.phid}&otype=edit&busType=EFORM9000000092&isSso=1&AppTitle=${encodeURIComponent("现场拜访记录-修改")}
                                            // &sourceId=${$NG.getCmpApi("p_form_visit_plan_d").getSelectedRow().phid}&inType=click`
                                            //         $NG.open(origin + param)
    
                                            //     }
                                        }
                                    })
                                })
                                

                            }
                        }
                        console.log('双击成功!!!!!', window.location.href);
                    }
                }
            }
        })
    })

    $NG.execServer("getInDate", {}, function (res) {
        if (res.count == 0) {
            $NG.alert("当前日期不在任何工作周期范围内")
        } else {
            console.log(res);
            const _data = JSON.parse(res.data)[0].extendObjects
            console.log(`获取当前的工作周期`, _data);
            $NG.updateState((updater) => {
                updater.data.p_form_visit_plan_m.setProps({
                    phid_cycle: {
                        label: _data.bill_name,
                        value: _data.phid
                    }
                })
            })
        }
    })
    useValuesChange(({ args }) => {
        console.log(`监听周期`, args[0]);
    })
    // 监听表格行为
    useUpdateRows(({ args }) => {
        console.log(`表格行为监听`, args);
        viewNum()
        setButton()
        const rows = JSON.parse(JSON.stringify(args[0]));
        const seenNames = new Set();  // 用于跟踪已出现的名称
        const duplicateIndices = [];  // 记录需要删除的重复项索引

        // 正向遍历，标记后续重复项
        rows.forEach((row, index) => {
            const name = row.u_plan_visit_ps_EXName;
            if (name == null) return;  // 忽略空值

            if (seenNames.has(name)) {
                duplicateIndices.push(index);  // 标记为重复项
            } else {
                seenNames.add(name);  // 记录首次出现的名称
            }
        });

        // 存在重复项时的处理逻辑
        if (duplicateIndices.length > 0) {
            $NG.alert(`计划回访对象中，已自动删除后续重复内容！`);

            // 反向删除避免索引错位
            duplicateIndices.reverse().forEach(index => {
                rows.splice(index, 1);
            });

            // 更新表格数据（确保异步顺序）
            grid.clearRows().then(() => {
                grid.addRows(rows);
                grid.refreshView();
            });
        }

        const row = args[0]
        let lock = false
        row.forEach(item => {
            item.u_dbclick = '双击跳转列表'
            if (item.u_visit_way !== '现场回访') {
                item.u_visit_way = "现场回访"
                lock = true
            }
            if (item.u_gxrzt !== '1') {
                item.u_gxrzt = `1`
                lock = true
            }
        })
        if (lock) {
            grid.refreshView()

        }
    }, "p_form_visit_plan_d")

    function viewNum() {
        $NG.updateState((updater) => {
            updater.data.p_form_visit_plan_m.setProps({
                u_plan_qty: grid.getRows().length,
            })
        })
    }
    // 监听表体编辑
    useUpdateRow(({ args }) => {
        // gxrDFilter(args[0].phid_pc)
        console.log(`监听编辑`, args, args[0].phid_pc != phidPc);
        if (args[0].phid_pc != phidPc) {
            phidPc = args[0].phid_pc
            args[0].u_plan_visit_ps = u_plan_visit_ps = null
            args[0].u_plan_visit_ps_EXName = null
            console.log(args[0].phid_pc);
            gxrDFilter(args[0].phid_pc)
            console.log(`gxrArr`, gxrArr);
        }
        gxrArr.forEach(item => {
            console.log('干系人', item);
            if (item.u_gxr == args[0].u_plan_visit_ps) {
                console.log(cityMap[item.pno], cityMap[item.cno]);
                args[0].u_provice = item.pno
                args[0].u_provice_EXName = cityMap[item.pno]
                args[0].u_city = item.cno
                args[0].u_city_EXName = cityMap[item.cno]
                args[0].u_telephine = item.u_mobile_phone
                args[0].u_khdw = item.gxr_dwmc
            }
        })
        console.log(`gxrScarr`, gxrScArr);
        // gxrScArr.forEach((item) => {
        //     if (item.u_gxr == args[0].u_plan_visit_ps) {
        //         args[0].u_schfqk = item.u_hfqk
        //         args[0].u_s_visit_time = item.u_time
        //     }
        // })
        grid.refreshView()
    }, "p_form_visit_plan_d")
    useDataIndexChange(({ args }) => {
        console.log(`监听干系人`, args[0]);
        gxrScArr.forEach((item) => {
            if (item.u_gxr == args[0].u_plan_visit_ps) {
                args[0].u_schfqk = item.schfqk
                args[0].u_s_visit_time = item.u_visit_time

            }
        })
    }, "u_plan_visit_ps")
    useDataIndexChange(({ args }) => {
        getPtInfoByPhid(args[0].phid_pc, (datas) => {
            args[0].u_xmlx = datas.type_phid,
                args[0].u_xmlx_EXName = datas.type_name
            grid.refreshView()
        })
    }, "phid_pc")
    // 监听事业部的变化
    setTimeout(() => {
        getGxrScInfo();
    }, 200);
    useValuesChange(({ args }) => {
        proDFilter()
        getGxrInfo()
        getGxrScInfo();

        // getGxrScInfo()
        if (page.oType = 'add') {
            home = args[0].phid_org.label
            setCurOrgid()
        }
    }, "p_form_visit_plan_m.phid_org")
    //     //监听工作周期
    // useValuesChange(({args})=>{
    //     console.log(`工作周期监听`,args[0]);
    //     if(page.oType = 'add'){
    //         dateIn = args[0].phid_cycle.label
    //         setCurOrgid()
    //     }
    // }, "p_form_visit_plan_m.phid_cycle")
    setTimeout(() => {
        console.log(`============`, mstform.getItem("phid_cycle").getText());
    }, 2000)
    //设置单据名称
    function setCurOrgid() {
        if (!mstform.getItem("phid_org").getValue() || !mstform.getItem("bill_dt").getValue()) return
        $NG.updateState((updater) => {
            updater.data.p_form_visit_plan_m.setProps({
                bill_name: `${home}事业部的${mstform.getItem("phid_cycle").getText()}统计周期现场拜访计划`
            })
        })
    }
    //根据项目ID获取项目相关信息
    function getPtInfoByPhid(phid, fun) {
        if (phid) {
            $NG.execServer("getPtInfoByPhid", { phid }, function (res) {
                console.log(`获取项目信息`, res, phid);
                const datas = JSON.parse(res.data)[0].extendObjects;
                console.log(datas);
                fun(datas)
            });
        }
    }

    //干系人过滤
    // gxrMFilter()
    // function gxrMFilter(){
    //     $NG.updateUI(updater => {
    //         console.log(updater,'过滤');
    //         updater.editGrid.p_form_visit_plan_m.u_plan_visit_ps.setProps((p) => {
    //             return {
    //               ...p, editor: {
    //                 ...p.editor,
    //                 clientSqlFilter: { gxr_where:"1" },
    //               }
    //             };
    //           })
    //     });
    // }

    // 按钮属性说明的设置
    function setButton() {
        const _arrD = grid.getRows()
        let _lock = false
        _arrD.forEach(item => {
            if (item.u_jump !== '新增拜访记录') {
                item.u_jump = '新增拜访记录'
                _lock = true
            } else { }
        })
        if (_lock) {
            grid.refreshView()
        }
    }
    // 获取省份信息
    function getAllGxr() {
        $NG.execServer("getAllCity", {}, function (res) {
            const _data = JSON.parse(res.data)
            console.log(`获取城市信息`, _data);
            const _map = {}
            _data.forEach(item => {
                const datas = item.extendObjects
                _map[datas.pid] = datas.pname
                _map[datas.cno] = datas.cname
            })
            cityMap = { ..._map }
        })
    }
    // 检查表是否已审核
    function currentStatus() {
        if ($NG.getPageState().data.p_form_visit_plan_m.app_status == 1) {
            return true
        } else {
            $NG.alert("单据未审核！")
            return false
        }
    }
    proDFilter()
    function proDFilter() {
        console.log(`proDFilter`);
        const phid_pcc = $NG.getCmpApi('p_form_visit_plan_m').getItem('phid_org').getValue();
        if (!phid_pcc) {
            return
        }
        $NG.updateUI(updater => updater.editGrid.p_form_visit_plan_d.phid_pc.setProps((p) => {
            return {
                ...p, editor: {
                    ...p.editor,
                    clientSqlFilter: { phid_org: $NG.getCmpApi('p_form_visit_plan_m').getItem('phid_org').getValue() },
                }
            };
        }));
    }
    gxrDFilter()
    function gxrDFilter(phid) {
        const phid_pcc = phid
        if (!phid_pcc) {
            return
        }
        $NG.updateUI(updater => updater.editGrid.p_form_visit_plan_d.u_plan_visit_ps.setProps((p) => {
            console.log(phid);
            return {
                ...p, editor: {
                    ...p.editor,
                    clientSqlFilter: { phid_pc: phid },
                }
            };
        }));
    }

    // 获取干系人信息
    function getGxrInfo(arg) {
        if (!mstform.getItem("phid_org").getValue()) return
        grid.refreshView()
        $NG.execServer("getAllFilterGxr", { phid_org: mstform.getItem("phid_org").getValue() }, function (res) {
            if (res.count == 0) return
            const datas = JSON.parse(res.data)
            console.log(`获取干系人组织`, datas);
            gxrArr = []
            datas.forEach(item => {
                gxrArr.push(item.extendObjects)
            })
            console.log(`gxrArr`, gxrArr, mstform.getItem("phid_org").getValue());
        })
    }
    // 获取干系人上一次的记录
    function getGxrScInfo() {
        if (!mstform.getItem("phid_org").getValue()) return
        grid.refreshView()
        $NG.execServer("getGxrScInfo", {}, function (res) {
            console.log(`获取干系人响应式数据`, res);
            if (res.count == 0) return
            const datas = JSON.parse(res.data)
            gxrScArr = []
            datas.forEach(item => {
                gxrScArr.push(item.extendObjects)
            })
        })
    }
    // 格式化日期
    // 格式化日期
    function formatDate(dateStr, outputFormat) {
        const date = new Date(dateStr);

        if (isNaN(date)) {
            return "无效的日期字符串";
        }

        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');

        let formattedDate;

        switch (outputFormat) {
            case "yyyy-mm-dd":
                formattedDate = `${year}-${month}-${day}`;
                break;
            case "yyyy-mm-dd HH:mm":
                formattedDate = `${year}-${month}-${day} ${hours}:${minutes}`;
                break;
            case "yyyy-mm":
                formattedDate = `${year}-${month}`;
                break;
            // 可以根据需要继续添加其他格式的处理逻辑
            default:
                formattedDate = "不支持的输出格式";
        }

        return formattedDate;
    }
});